//package com.ruoyi.video.service.impl;
//
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.util.*;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.atomic.AtomicReference;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//import java.util.stream.Collectors;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
////import com.ruibty.nsfw.NsfwService;
//import com.ruibty.nsfw.NsfwService;
//import com.ruoyi.common.core.constant.SecurityConstants;
//import com.ruoyi.common.core.context.SecurityContextHolder;
//import com.ruoyi.common.core.utils.DateUtils;
//import com.ruoyi.common.core.utils.StringUtils;
//import com.ruoyi.common.core.utils.bean.BeanUtils;
//import com.ruoyi.common.core.web.page.TableDataInfo;
//import com.ruoyi.system.api.model.LoginUser;
//import com.ruoyi.video.domain.*;
//import com.ruoyi.video.dto.ImageTextTapVo;
//import com.ruoyi.video.dto.ImageTextVo;
//import com.ruoyi.video.dto.VideoIdsVO;
//import com.ruoyi.video.dto.circle.QueryVO;
//import com.ruoyi.video.mapper.MediaCircleMapper;
//import com.ruoyi.video.service.IMediaNotifyService;
//import com.ruoyi.video.utils.MinioUtil;
//import com.ruoyi.video.utils.ThreadUtil;
//import com.ruoyi.video.vConst.IPAddrConst;
//import lombok.AllArgsConstructor;
//import lombok.Data;
//import lombok.NoArgsConstructor;
//import okhttp3.*;
//import org.elasticsearch.action.bulk.BulkRequest;
//import org.elasticsearch.action.delete.DeleteRequest;
//import org.elasticsearch.action.delete.DeleteResponse;
//import org.elasticsearch.action.index.IndexRequest;
//import org.elasticsearch.client.RequestOptions;
//import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.common.xcontent.XContentType;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.core.SetOperations;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.scheduling.annotation.EnableAsync;
//import org.springframework.stereotype.Service;
//import com.ruoyi.video.mapper.ImageTextMapper;
//import com.ruoyi.video.service.IImageTextService;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.annotation.Resource;
//
///**
// * 【请填写功能名称】Service业务层处理
// *
// * @author ruoyi
// * @date 2024-05-11
// */
//@Service
//public class ImageTextServiceImpl implements IImageTextService
//{
//    @Autowired
//    private MinioUtil minioUtil;
//    @Autowired
//    private MediaFilesServiceImpl mediaFilesService;
//    @Resource
//    private ImageTextMapper imageTextMapper;
//    @Resource
//    private RedisTemplate redisTemplate;
//
//    @Autowired
//    RestHighLevelClient restHighLevelClient;
//    List<ImageTextVo> listimageTextVo;
//    private OkHttpClient client = new OkHttpClient();
//    final String baseUrl = "http://192.168.0.160:6307/api/nsfw/classify?url=";
//    @Resource
//    MediaCircleMapper mediaCircleMapper;
//    /**
//     * 查询【请填写功能名称】
//     *
//     * @param id 【请填写功能名称】主键
//     * @return 【请填写功能名称】
//     */
//    @Override
//    public ImageTextVo selectImageTextById(Long id)
//    {
//        ImageText imageText = imageTextMapper.selectImageTextById(id);
//        MediaCircle mediaCircle = mediaCircleMapper.selectMediaCircleByCircleId(imageText.getCircleId());
//        List<String> items = Arrays.asList(imageText.getMediaFileIds().split(";"));
//        ImageTextVo imageTextVo = new ImageTextVo();
//        imageTextVo.setCircleId(mediaCircle.getCircleId());
//        imageTextVo.setCirleName(mediaCircle.getCirclName());
//        BeanUtils.copyProperties(imageText,imageTextVo);
//        items = items.stream().map(item2 -> {
//            String imgUrl;
//            if(item2.length()>0&&!item2.equals("")) {
//                //判断图片文件是否违规，如果违规设置违规图片
//                String item2Id = item2.substring(item2.lastIndexOf("/")+1,item2.lastIndexOf("."));
//                MediaFiles mediaFile = mediaFilesService.selectMediaFilesById(item2Id);
//                if(mediaFile !=null && mediaFile.getStatus().equals("0") ) {
//                    imgUrl = minioUtil.previewImage("6/4/6476c66286aacb9fd2db3ea44e6b1b40/6476c66286aacb9fd2db3ea44e6b1b40.png");
//                } else {
//                    imgUrl = minioUtil.previewImage(item2);
//
//                }
//                return regReplace(imgUrl, "http://192.168.0.160:9000", IPAddrConst.VIPADDR);
//
//            } else {
//                return regReplace( minioUtil.previewImage("6/4/6476c66286aacb9fd2db3ea44e6b1b40/6476c66286aacb9fd2db3ea44e6b1b40.png"), "http://192.168.0.160:9000", IPAddrConst.VIPADDR);
//
//            }
//
//
////                return regReplace(imgUrl, "http://192.168.0.160:9000", IPAddrConst.IMAGEIPADDR);
//        }).collect(Collectors.toList());
//        imageTextVo.setMediaFileIds(items);
//        return imageTextVo;
//    }
//    public String regReplace(String content,String pattern,String newString){
//        Pattern p = Pattern.compile(pattern);
//        Matcher m = p.matcher(content);
//        String result = m.replaceAll(newString);
//        return result;
//    }
//    /**
//     * 查询【请填写功能名称】列表
//     *
//     * @param imageText 【请填写功能名称】
//     * @return 【请填写功能名称】
//     */
//    @Override
//    public List<ImageTextVo> selectImageTextList(ImageText imageText)
//    {
//
//        listimageTextVo = new ArrayList<>();
//        List<ImageText> imageTextList = imageTextMapper.selectImageTextList(imageText);
//
//        listimageTextVo = imageTextList.stream().map(item -> {
//            ImageTextVo imageTextVo = new ImageTextVo();
//
//            BeanUtils.copyProperties(item,imageTextVo);
//            List<String> items = Arrays.asList(item.getMediaFileIds().split(";"));
//            items = items.stream().map(item2 -> {
//                String imgUrl;
//                if(item2.length()>0&&!item2.equals("")) {
//                    //判断图片文件是否违规，如果违规设置违规图片
//                    String item2Id = item2.substring(item2.lastIndexOf("/")+1,item2.lastIndexOf("."));
//                    MediaFiles mediaFile = mediaFilesService.selectMediaFilesById(item2Id);
//                    if(mediaFile !=null && mediaFile.getStatus().equals("0") ) {
//                        imgUrl = minioUtil.previewImage("6/4/6476c66286aacb9fd2db3ea44e6b1b40/6476c66286aacb9fd2db3ea44e6b1b40.png");
//                    } else {
//                        imgUrl = minioUtil.previewImage(item2);
//
//                    }
//                    return regReplace(imgUrl, "http://192.168.0.160:9000", IPAddrConst.VIPADDR);
//
//                } else {
//                    return regReplace( minioUtil.previewImage("6/4/6476c66286aacb9fd2db3ea44e6b1b40/6476c66286aacb9fd2db3ea44e6b1b40.png"), "http://192.168.0.160:9000", IPAddrConst.VIPADDR);
//
//                }
//
//
////                return regReplace(imgUrl, "http://192.168.0.160:9000", IPAddrConst.IMAGEIPADDR);
//            }).collect(Collectors.toList());
//            imageTextVo.setMediaFileIds(items);
//            return imageTextVo;
//        }).collect(Collectors.toList());
//        return listimageTextVo;
//    }
//
//    /**
//     * 新增【请填写功能名称】
//     *
//     * @param imageText 【请填写功能名称】
//     * @return 结果
//     */
//    @Override
//    @Transactional
//    public int insertImageText(ImageText imageText)
//    {
//
//
//        LoginUser loginUser = SecurityContextHolder.get(SecurityConstants.LOGIN_USER,LoginUser.class);
//        imageText.setLikeCount(0l);
//        Long userId = loginUser.getUserid();
//        imageText.setState("1");
//        String key = "image_md5_set"+userId;
//        SetOperations<String, String> setOps = redisTemplate.opsForSet();
//        Set<String> imageUrls = setOps.members(key);
//        //鉴黄
////        filteringNSFW(imageUrls);
//        String imageUrlString = imageUrls.stream().collect(Collectors.joining(";"));
////        从redis中获取图片源
//        imageText.setMediaFileIds(imageUrlString);
////        System.out.println("mediaFileIds"+imageUrlString);
//        imageText.setCreateTime(DateUtils.getNowDate());
//        imageText.setPubId(userId);
//        imageText.setLikeCount(0L);
//        Integer result = imageTextMapper.insertImageText(imageText);
//        redisTemplate.delete(key);
//        imageTextMapper.selectImageTextById(imageText.getId());
//        try {
//            BulkRequest bulkRequest = new BulkRequest("app_info_image_text");
//            IndexRequest indexRequest = new IndexRequest().id(imageText.getId().toString())
//                    .source(JSON.toJSONString(imageText), XContentType.JSON);
//
//            bulkRequest.add(indexRequest);
//            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
//        } catch (Exception e) {
//
//        }
//
//        return result;
//    }
//
//    @Resource
//    private NsfwService nsfwService;
//
//    @Transactional
//    void filteringNSFW(Set<String> imageUrls) {
//        List<String> results = new ArrayList<>();
//
//
//        imageUrls.stream().map(item -> {
//            String imgUrl = minioUtil.previewImage(item);
//            boolean isExi = false;
//            String id = imgUrl.substring(imgUrl.lastIndexOf("/")+1,imgUrl.lastIndexOf("."));
//            String url = baseUrl + item;
//            MediaFiles mediaFiles = new MediaFiles();
//
//            Request request = new Request.Builder()
//                    .url(imgUrl)
//                    .build();
//            try {
//                // 创建请求对象
//
//                ResponseBody responseBody = client.newCall(request).execute().body();
////                if(responseBody != null) {
////                    byte[] imageBytes = responseBody.bytes();
////                    String base64Image = Base64.getEncoder().encodeToString(imageBytes);
////
////                    // 创建请求体
////                    String requestBody1 = "{\"instances\": [{\"b64\": \"" + base64Image + "\"}]}";
////                    RequestBody requestBodyt = RequestBody.create(MediaType.parse("application/json"), requestBody1);
////
////                    // 创建请求对象
////                    Request request1 = new Request.Builder()
////                            .url(IPAddrConst.NSFWADDR)
////                            .addHeader("Content-Type", "application/json")
////                            .post(requestBodyt)
////                            .build();
////                    ResponseBody responseBody1 = client.newCall(request1).execute().body();
////                    PrivateDetector nsfwObjectList = JSONArray.parseObject(responseBody1.string(),PrivateDetector.class);
////                    Double prediction = nsfwObjectList.getPredictions().get(0)[0];
////                    if(prediction >= 0.5) {
////                        mediaFiles.setId(id);
////                        mediaFiles.setStatus("0");
////                        mediaFilesService.updateMediaFiles(mediaFiles);
////                    }
////                }
//
//
//
//
////                    if (responseBody != null) {
////                        String respon = responseBody.string();
////                        List<NSFWObject> nsfwObjectList = JSONArray.parseArray(respon,NSFWObject.class);
////
////                        Double maxValue = 0.0d;
////                        for (NSFWObject nsfwObject : nsfwObjectList) {
////                            String objName = nsfwObject.getClassName();
////                            Double probability = nsfwObject.getProbability();
////                            if(objName.equals("Sexy") || objName.equals("Porn")) {
////                                maxValue = maxValue + probability;
////                                if(maxValue >= 0.4) {
////                                    mediaFiles.setId(id);
////                                    mediaFiles.setStatus("0");
////                                    mediaFilesService.updateMediaFiles(mediaFiles);
////                                }
////
////                            }
////                        }
////                        if(nsfwObjectList.get(4).getProbability() >= 0.6
////                                || nsfwObjectList.get(3).getProbability() >= 0.6) {
////
////                        }
////                        System.out.println(nsfwObjectList.size());
////                    }
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            return item;
//
//        }).collect(Collectors.toList());
//    }
//
//    /**
//     * 修改【请填写功能名称】
//     *
//     * @param imageText 【请填写功能名称】
//     * @return 结果
//     */
//    @Override
//    public int updateImageText(ImageText imageText)
//    {
//        imageText.setUpdateTime(DateUtils.getNowDate());
//        return imageTextMapper.updateImageText(imageText);
//    }
//
//    /**
//     * 批量删除【请填写功能名称】
//     *
//     * @param ids 需要删除的【请填写功能名称】主键
//     * @return 结果
//     */
//    @Override
//    public int deleteImageTextByIds(Long[] ids)
//    {
//        return imageTextMapper.deleteImageTextByIds(ids);
//    }
//
//    /**
//     * 删除【请填写功能名称】信息
//     *
//     * @param id 【请填写功能名称】主键
//     * @return 结果
//     */
//    @Transactional
//    @Override
//    public int deleteImageTextById(Long id)
//    {
//        Long userId = SecurityContextHolder.getUserId();
//        ImageText imageText = imageTextMapper.selectImageTextById(id);
//        if(userId.longValue() != imageText.getPubId().longValue()) return 0;
//        try {
//            int result = imageTextMapper.deleteImageTextById(id);
//            String imageTextId = id.toString();
//            DeleteRequest request = new DeleteRequest("app_info_image_text",imageTextId);
//            //文档id
//            DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
//
//        } catch (Exception e) {
//
//        }
//        //删除文本，删除el,删除
//        return 1;
//    }
//
//    @Override
//    public Long selectImageTextListTotal() {
//        Long count = imageTextMapper.selectImageTextCount();
//        return count;
//    }
//
//    @Override
//    public List<String> selectImageTextPreviewByIds(VideoIdsVO imageTextIds) {
//        List<String> urls = new ArrayList<>();
//        imageTextIds.getImageTextIds().stream().map(item -> {
//            ImageText imageText = imageTextMapper.selectImageTextById(item.longValue());
//
//            List<String> items = Arrays.asList(imageText.getMediaFileIds().split(";"));
//            for(String tempitem : items) {
//                if(StringUtils.isNotEmpty(tempitem)) {
//                    String imgUrl = minioUtil.previewImage(tempitem);
//                    imgUrl = regReplace(imgUrl, "http://192.168.0.160:9000", IPAddrConst.VIPADDR);;
//                    urls.add(imgUrl);
//                } else {
//                    urls.add(regReplace(minioUtil.previewImage("6/4/6476c66286aacb9fd2db3ea44e6b1b40/6476c66286aacb9fd2db3ea44e6b1b40.png"), "http://192.168.0.160:9000", IPAddrConst.VIPADDR));
//                }
//
//                break;
//            }
//            return item;
//        }).collect(Collectors.toList());
//        return urls;
//    }
//    @Resource
//    private IMediaNotifyService iMediaNotifyService;
//    @Override
//    public Integer tapUp(ImageTextTapVo imageTextTapVo) {
//        MediaNotify mediaNotify = new MediaNotify();
//        mediaNotify.setImageTextId(imageTextTapVo.getImageTextId());
//        mediaNotify.setIsReady(0);
//        mediaNotify.setType(2L);
//        mediaNotify.setFromUid(imageTextTapVo.getFromUid());
////        ImageText imageText = new ImageText();
//        LikeTapEntity likeTapEntity = new LikeTapEntity();
//        likeTapEntity.setImageTextId(imageTextTapVo.getImageTextId());
//        likeTapEntity.setFromUid(imageTextTapVo.getFromUid());
//        likeTapEntity.setRandomNumber(imageTextTapVo.getRandomNumber());
//        Integer i = imageTextMapper.addLikeCount(likeTapEntity);
//        iMediaNotifyService.insertMediaNotify(mediaNotify);
//        return i;
//    }
//
//    @Override
//    public List<ImageTextVo> selectImageTextList1(String orderKey,Long circlId) {
//        QueryVO queryVO = new QueryVO();
//        queryVO.setCirclId(circlId);
//        queryVO.setOrderKey(orderKey);
//        listimageTextVo = new ArrayList<>();
//        List<ImageText> imageTextList = imageTextMapper.selectImageTextList1(queryVO);
//        listimageTextVo = imageTextList.stream().map(item -> {
//            ImageTextVo imageTextVo = new ImageTextVo();
//            MediaCircle mediaCircle = mediaCircleMapper.selectMediaCircleByCircleId(item.getCircleId());
//
//            imageTextVo.setCircleId(mediaCircle.getCircleId());
//            imageTextVo.setCirleName(mediaCircle.getCirclName());
//            BeanUtils.copyProperties(item,imageTextVo);
//            List<String> items = Arrays.asList(item.getMediaFileIds().split(";"));
//            items = items.stream().map(item2 -> {
//                String imgUrl;
//                if(item2.length()>0&&!item2.equals("")) {
//                    //判断图片文件是否违规，如果违规设置违规图片
//                    String item2Id = item2.substring(item2.lastIndexOf("/")+1,item2.lastIndexOf("."));
//                    MediaFiles mediaFile = mediaFilesService.selectMediaFilesById(item2Id);
//                    if(mediaFile !=null && mediaFile.getStatus().equals("0") ) {
//                        imgUrl = minioUtil.previewImage("6/4/6476c66286aacb9fd2db3ea44e6b1b40/6476c66286aacb9fd2db3ea44e6b1b40.png");
//                    } else {
//                        imgUrl = minioUtil.previewImage(item2);
//
//                    }
//                    return regReplace(imgUrl, "http://192.168.0.160:9000", IPAddrConst.IMAGEIPADDR);
//
//                } else {
//                    return regReplace( minioUtil.previewImage("6/4/6476c66286aacb9fd2db3ea44e6b1b40/6476c66286aacb9fd2db3ea44e6b1b40.png"), "http://192.168.0.160:9000", IPAddrConst.VIPADDR);
//
//                }
//
//
////                return regReplace(imgUrl, "http://192.168.0.160:9000", IPAddrConst.IMAGEIPADDR);
//            }).collect(Collectors.toList());
//            imageTextVo.setMediaFileIds(items);
//            return imageTextVo;
//        }).collect(Collectors.toList());
//        return listimageTextVo;
//
//    }
//
//    @Override
//    public Long selectCountCircle(Long circlId) {
//
//        return imageTextMapper.selectImageTextCountByCircleId(circlId);
//    }
//}
//
//@Data
//class PrivateDetector {
//    List<Double[]> predictions;
//}
//@Data
//class ListNSFWObject {
//    private List<NSFWObject> nsfwObjectList;
//}
//@Data
//@AllArgsConstructor
//@NoArgsConstructor
//class NSFWObject {
//    private String className;
//    private Double probability;
//}
//
//
//
